﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KhuyenMaiVang.DAL;
using KhuyenMaiVang.Models;
using System.Web.Routing;

namespace KhuyenMaiVang.Controllers
{
    public class HomeController : Controller
    {
        const int NumPerPage = 9;
        const int NumPaging = 10;
        KhuyenMaiVangDataContext db = new KhuyenMaiVangDataContext();
        DataProvider provider = new DataProvider();

        public ActionResult Index()
        {
            ViewBag.TempDataSuccess = (String)TempData["success"];
            return View();
        }
        [HttpPost]
        public ActionResult Index(UserMail uMail)
        {
            db.UserMails.AddObject(uMail);
            db.SaveChanges();
            ViewBag.TempDataSuccess = "Bạn đã đăng ký email " +uMail.Email+ " thành công";
            return View();
        }
        public ActionResult DealsToDay(int city = -1, int category = -1)
        {
            var vouchers = provider.DealsToDay(city, category, NumPerPage);
            return View(vouchers);
        }

        public ActionResult DealsRecent(int city = -1, int category=-1, int page = 1, int numPerPage = NumPerPage)
        {
            PagingModel pagingModel = null;
            var query = provider.DealsRecent(city, category);
            int totalVouchers = query.Count();
            var vouchers = query.Skip((page - 1) * numPerPage).Take(NumPerPage).ToArray();

            var routes = new RouteValueDictionary();
            routes.Add("city", city);
            routes.Add("category", category);
            pagingModel = new PagingModel("Home", "DealsRecent", routes, page, totalVouchers, NumPerPage, NumPaging);
            ViewBag.PagingModel = pagingModel;
            return View(vouchers);
        }

        public ActionResult VoucherDetail(int id)
        {
            Voucher voucher = provider.GetVoucher(id);
            if (voucher == null)
                Redirect("/Home/DealsToDay");
            return View(voucher);
        }
    }
}
